package com.example.shop_2208.fragment

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.shop_2208.R
import com.example.shop_2208.adapter.MyAdapter
import com.example.shop_2208.databinding.FragmentMineBinding
import com.example.shop_2208.db.MyDbUtils
import com.example.shop_2208.mvvm.BaseFragment
import com.example.shop_2208.mvvm.BaseViewFragment
import com.example.shop_2208.utils.GlideUtils
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.wildma.pictureselector.PictureBean
import com.wildma.pictureselector.PictureSelector
import kotlinx.coroutines.launch
import okhttp3.HttpUrl
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File

class MineFragment : BaseFragment<FragmentMineBinding, MineViewModel>() {
    val list = mutableListOf<Fragment>()
    val titles = mutableListOf<String>()
    lateinit var myAdapter: MyAdapter
    override fun initData() {
        viewModel.success.observe(this){
            ToastUtils.showLong(it.message)
        }
    }
    override fun initView() {
        lifecycleScope.launch {
            binding.user = MyDbUtils.getDb().getUserDao().getUserById(SPUtils.getInstance().getInt("id"))
        }

        list.add(PayingFragment())
        list.add(PayedFragment())
        titles.add("待支付")
        titles.add("已支付")
        myAdapter = MyAdapter(requireActivity(),list)
        binding.vp.adapter = myAdapter

        TabLayoutMediator(binding.tab,binding.vp
        ) { tab, position -> tab.text = titles[position] }.attach()
        //点击我的头像，变更图片
        binding.userIcon.setOnClickListener {
            PictureSelector.create(this,103).selectPicture()//弹出具体图片
        }
    }

    override fun getViewModel(): Class<MineViewModel>  = MineViewModel::class.java

    override fun getLayout(): Int  = R.layout.fragment_mine
    //显示具体图片
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode==103&&resultCode==Activity.RESULT_OK){
            val pictureBean = data?.extras?.get(PictureSelector.PICTURE_RESULT) as PictureBean//拿到图片
            context?.let { GlideUtils.loadCircleImage(it,binding.userIcon,pictureBean.path) }//显示到页面

            //调用更新后台
            val body = RequestBody.create(
                "multipart/form-data".toMediaType(),
                File(pictureBean.path)
            )
            val part = MultipartBody.Part.createFormData("file","abc.jpg",body)
            viewModel.updateIcon(part)
        }
    }

}